package com.drools.util;

import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Json 工具类，封装 gson，代替 fastjson
 *
 * @author zhouchaoqun02
 * @date 2020-03-20 20:11
 */
public class JsonUtil {

    private static final Gson gson = new Gson();

    private JsonUtil() {
    }

    public static String toJsonString(Object object) {
        return gson.toJson(object);
    }


    public static <T> T parseObject(String jsonString, Class<T> clazz) {
        return gson.fromJson(jsonString, clazz);
    }

    public static <T> List<T> parseArray(String json, Class<T> clazz) {
        ListParameterizedType type = new ListParameterizedType(clazz);
        return gson.fromJson(json, type);
    }

    private static class ListParameterizedType implements ParameterizedType {
        private Type type;
        private ListParameterizedType(Type type) {
            this.type = type;
        }
        @Override
        public Type[] getActualTypeArguments() {
            return new Type[] {type};
        }
        @Override
        public Type getRawType() {
            return ArrayList.class;
        }
        @Override
        public Type getOwnerType() {
            return null;
        }
    }
}
